package com.luyishi.controller;

import com.luyishi.entity.User;
import com.luyishi.service.IUserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author Lenovo
 * @Date: 2020/8/20 17:48
 */
@Controller
public class UserController {

    @Resource
    private IUserService userService;

    @GetMapping("/getallusers")
    @ResponseBody
    public List<User> getAllUser(){
        return userService.getUserInfo();
    };

    @GetMapping("/repetitive")
    @ResponseBody
    public String repetitiveUsername(String username){
        boolean hasUsername = userService.repetitiveUsername(username);
        if (hasUsername){
            return "true";
        } else {
            return null;
        }
    }

    @GetMapping(value = "/register")
    public String toRegister(){
        return "user/register";
    }

    @PostMapping(value = "/register")
    @ResponseBody
    public String doRegister(String username, String password){
        System.out.println(username + " " + password );
        String result = null;
        if (!"".equals(username) || !"".equals(password)){
            boolean hasUsername = userService.repetitiveUsername(username);
            System.out.println(hasUsername);
            if (hasUsername){
                boolean isRegister = userService.register(username, password);
                if (isRegister){
                    result = "true";
                }
            }
        }
        return result;
    }

    @GetMapping(value = "/registerSuccess")
    public String toRegisterSuccess(){
        return "user/registerSuccess";
    }

    @GetMapping(value = "/login")
    public String toLogin(){
        return "user/login";
    }

    @PostMapping(value = "/login")
    @ResponseBody
    public String doLogin(String username, String password, ModelMap modelMap){
        User user = userService.login(username, password);
        String result = null;
        if (user != null){
            modelMap.addAttribute("USER_SESSION",user);
            result = "true";
        }
        return result;
    }

}
